package com.yby.mall.storage.exception;

import com.yby.common.exception.ExceptionCodeEnum;
import com.yby.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;

/**
 * 集中处理异常
 */

@Slf4j
@RestControllerAdvice(basePackages = "com.yby.mall.storage.controller")
public class MallProductException {

    @ExceptionHandler(value = RuntimeException.class)
    public R runtimeException(RuntimeException runtimeException) {
        runtimeException.printStackTrace();
        if (runtimeException instanceof NullPointerException) {
            return R.error(ExceptionCodeEnum.NULLPOINTEREXCEPTION.getCode(), ExceptionCodeEnum.NULLPOINTEREXCEPTION.getMsg());
        } else if (runtimeException instanceof ClassCastException) {
            return R.error(ExceptionCodeEnum.CLASSCASTEXCEPTION.getCode(), ExceptionCodeEnum.CLASSCASTEXCEPTION.getMsg());
        } else if (runtimeException instanceof NegativeArraySizeException) {
            return R.error(ExceptionCodeEnum.NEGATIVEARRAYEXCEPTION.getCode(), ExceptionCodeEnum.NEGATIVEARRAYEXCEPTION.getMsg());
        } else if (runtimeException instanceof IndexOutOfBoundsException) {
            return R.error(ExceptionCodeEnum.INDEXOUTOFBOUNDSEXCEPTION.getCode(), ExceptionCodeEnum.INDEXOUTOFBOUNDSEXCEPTION.getMsg());
        } else if (runtimeException instanceof ArrayIndexOutOfBoundsException) {
            return R.error(ExceptionCodeEnum.ARRAYINDEXOUTOFBOUNDSEXCEPTION.getCode(), ExceptionCodeEnum.ARRAYINDEXOUTOFBOUNDSEXCEPTION.getMsg());
        } else if (runtimeException instanceof IllegalArgumentException) {
            return R.error(ExceptionCodeEnum.ILLEGALACCESSEXCEPTION.getCode(), ExceptionCodeEnum.ILLEGALACCESSEXCEPTION.getMsg());
        }
        return R.error(ExceptionCodeEnum.UNKNOW_EXCEPTION.getCode(), ExceptionCodeEnum.UNKNOW_EXCEPTION.getMsg());
    }

    @ExceptionHandler(value = SQLException.class)
    public R sqlException(SQLException sqlException) {
        sqlException.printStackTrace();
        return R.error(ExceptionCodeEnum.SQLEXCEPTION.getCode(), ExceptionCodeEnum.SQLEXCEPTION.getMsg());
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable) {
        throwable.printStackTrace();
        return R.error(ExceptionCodeEnum.UNKNOW_EXCEPTION.getCode(), throwable.getMessage());
    }
}
